<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="实体名称" prop="entityName">
        <el-input
          v-model="queryParams.entityName"
          placeholder="请输入实体名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="实体标题" prop="entityTitle">
        <el-input
          v-model="queryParams.entityTitle"
          placeholder="请输入实体标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:entity:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:entity:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:entity:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="entityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="实体id" align="center" prop="entityId" />
      <el-table-column label="实体名称" align="center" prop="entityName" />
      <el-table-column label="实体标题" align="center" prop="entityTitle" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:entity:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:entity:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据实体对话框 -->
    <el-drawer v-model="open" size="85%">
      <template #header>
        <h4>{{title}}</h4>
      </template>
      <template #default>
        <el-form ref="entityRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="实体名称" prop="entityName">
            <el-input v-model="form.entityName" placeholder="请输入实体名称" />
          </el-form-item>
          <el-form-item label="实体标题" prop="entityTitle">
            <el-input v-model="form.entityTitle" placeholder="请输入实体标题" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" />
          </el-form-item>
          <el-form-item label="数据结构" prop="remark">
            <div class="meta">
              <el-tree
                  :data="form.meta"
                  node-key="tid"
                  default-expand-all
                  :expand-on-click-node="false"
                  :highlight-current="false"
              >
                <template #default="{ node, data }">
                  <div class="node">
                    <div class="node-name">
                      <el-input v-model="data.fieldName" placeholder="字段名" :disabled="data.sysField == '1'"/>
                    </div>
                    <div class="node-type">
                      <el-select v-model="data.fieldType" :disabled="data.sysField == '1'" @change="changeMetaFieldType(data)" style="width: 120px" placeholder="类型" clearable>
                        <el-option v-for="dict in magic_field_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
                      </el-select>
                      <template v-if="data.fieldType == 'array'">
                        <span style="font-size: 18px; margin: 0px 10px">/</span>
                        <el-select v-model="data.itemsType" :disabled="data.sysField == '1'" @change="changeMetaItemsType(data)" style="width: 120px" placeholder="元素类型" clearable>
                          <template v-for="dict in magic_field_type">
                            <el-option v-if="dict.value != 'array'" :key="dict.value" :label="dict.label" :value="dict.value"/>
                          </template>
                        </el-select>
                      </template>
                    </div>
                    <div class="node-title">
                      <el-input v-model="data.fieldTitle" placeholder="中文"  :disabled="data.sysField == '1'"/>
                    </div>
                    <div class="node-remark">
                      <el-input v-model="data.remark" placeholder="备注"  :disabled="data.sysField == '1'"/>
                    </div>
                    <div class="node-item1">
                      <el-button link type="primary" icon="Plus" @click="addMetaFieldNode(node, data)">相邻节点</el-button>
                      <el-button link type="primary" icon="Plus" @click="addMetaFieldChildrenNode(data)"
                                 v-if="data.fieldType == 'obj' || data.itemsType == 'obj'">
                        子节点
                      </el-button>
                      <el-button link type="primary" icon="Minus" @click="removeMetaFieldNode(node, data)">移除节点</el-button>
                    </div>
                  </div>
                </template>
              </el-tree>
            </div>

          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="Entity">
import { listEntity, getEntity, delEntity, addEntity, updateEntity } from "@/api/system/magicEntity";
import { copy } from "@/utils/tools"

const { proxy } = getCurrentInstance();

const { magic_field_type } = proxy.useDict("magic_field_type");

const entityList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    entityName: null,
    entityTitle: null,
  },
  rules: {
    entityName: [
      { required: true, message: "实体名称不能为空", trigger: "blur" }
    ],
    entityTitle: [
      { required: true, message: "实体标题不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 默认元信息 */
const defaultMetaData = [
  {
    "tid": new Date().getTime(),
    "fieldName": "id",
    "fieldTitle": "ID",
    "fieldType": "string",
    "sysField": "1",
    "required": "1",
    "remark": "系统字段"
  },
  {
    "tid": new Date().getTime(),
    "fieldName": "deptId",
    "fieldTitle": "部门id",
    "fieldType": "number",
    "sysField": "1",
    "required": "1",
    "remark": "系统字段"
  },
  {
    "tid": new Date().getTime(),
    "fieldName": "createTime",
    "fieldTitle": "创建时间",
    "fieldType": "datetime",
    "sysField": "1",
    "required": "1",
    "remark": "系统字段"
  },
  {
    "tid": new Date().getTime(),
    "fieldName": "createBy",
    "fieldTitle": "创建人",
    "fieldType": "number",
    "sysField": "1",
    "required": "1",
    "remark": "系统字段"
  },
  {
    "tid": new Date().getTime(),
    "fieldName": "updateTime",
    "fieldTitle": "更新时间",
    "fieldType": "datetime",
    "sysField": "1",
    "required": "1",
    "remark": "系统字段"
  },
  {
    "tid": new Date().getTime(),
    "fieldName": "updateBy",
    "fieldTitle": "更新人",
    "fieldType": "number",
    "sysField": "1",
    "required": "1",
    "remark": "系统字段"
  }
]

function getEmptyMetaField() {
  let field = {
    "tid": new Date().getTime(),
    "fieldName": "",
    "fieldTitle": "",
    "fieldType": "string",
    "sysField": "0",
    "required": "0",
    "remark": "",
  }
  return field;
}

/** 查询数据实体列表 */
function getList() {
  loading.value = true;
  listEntity(queryParams.value).then(response => {
    entityList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    entityId: null,
    entityName: null,
    entityTitle: null,
    meta: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("entityRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.entityId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  initMeta();
  open.value = true;
  title.value = "添加数据实体";
}

/** 初始化元信息 */
function initMeta() {
  let data = copy(defaultMetaData)
  data.push(getEmptyMetaField())
  form.value.meta = data
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _entityId = row.entityId || ids.value
  getEntity(_entityId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改数据实体";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["entityRef"].validate(valid => {
    if (valid) {
      if (form.value.entityId != null) {
        updateEntity(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addEntity(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _entityIds = row.entityId || ids.value;
  proxy.$modal.confirm('是否确认删除数据实体编号为"' + _entityIds + '"的数据项？').then(function() {
    return delEntity(_entityIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 添加相邻节点 */
function addMetaFieldNode(node, data) {
  const parent = node.parent
  const children = parent.data.children || parent.data
  const index = children.findIndex((d) => d.tid === data.tid)
  children.splice(index, 0, getEmptyMetaField())
  form.value.meta = [...form.value.meta]
}
/** 添加子节点 */
function addMetaFieldChildrenNode(data) {
  console.log(data)
  if (!data.children) {
    data.children = []
  }
  data.children.push(getEmptyMetaField())
  form.value.meta = [...form.value.meta]

}

/** 删除元信息节点 */
function removeMetaFieldNode(node, data) {
  const parent = node.parent
  const children = parent.data.children || parent.data
  const index = children.findIndex((d) => d.id === data.id)
  children.splice(index, 1)
  form.value.meta = [...form.value.meta]
}

/** 变更字段类型事件 */
function changeMetaFieldType(row) {
  if (row.fieldType == 'obj') {
    addMetaFieldChildrenNode(row)
  } else {
    row.children = null
  }
}

/** 变更数组元素类型事件 */
function changeMetaItemsType(row) {
  if (row.itemsType == 'obj') {
    row.children = [getEmptyMetaField()]
  } else {
    row.children = null
  }
}


getList();
</script>

<style lang="less" scoped>
.field {
  width: 100px;
}
.meta{
  width: 100%;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-sizing: border-box;
  padding: 10px;

  .node {
    width: 90%;
    display: flex;
    flex-direction: row;
    margin: 10px 0px;

    .node-name {
      flex: 1;
    }
    .node-title {
      width: 150px;
    }
    .node-type {
      width: 300px;
    }
    .node-remark {
      width: 150px;
    }
  }

  /deep/.el-input__wrapper {
    box-shadow: none!important;
    background-color: transparent!important;
    color: #2b2f3a!important;
  }
  /deep/.el-input__inner {
    color: #2b2f3a!important;
    -webkit-text-fill-color: #2b2f3a!important;
  }

  /deep/.el-tree-node__content {
    height: 45px!important;
    border-bottom: 1px solid #ccc;
  }
}
</style>